package com.juno.cafenoa.cart;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.juno.cafenoa.CafeNoa;
import com.juno.cafenoa.Constants;
import com.juno.cafenoa.R;
import com.juno.ui.uitableview.model.IListItem;
import com.juno.ui.uitableview.model.ViewItem;

public class CartTableView extends LinearLayout {

	private Context context;
	private int indexController = 0;
	private LayoutInflater rowInflater;
	private LinearLayout listContainer;
	private LinearLayout viewListContainer;
	private List<IListItem> cartList;
	private ClickListener mClickListener;
	public final int MAX_COFFEE_AMOUNT = 99;
	public final int MIN_COFFEE_AMOUNT = 1;
	public final int MAX_ADDITIONAL_AMOUNT = 99;
	public final int MIN_ADDITIONAL_AMOUNT = 0;

	public CartTableView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		cartList = new ArrayList<IListItem>();
		rowInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		listContainer = (LinearLayout) rowInflater.inflate(
				R.layout.list_container, null);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT);
		addView(listContainer, params);
		viewListContainer = (LinearLayout) listContainer
				.findViewById(R.id.buttonsContainer);
	}

	public void commit() {
		indexController = 0;

		if (cartList.size() > 1) {
			// when the list has more than one item
			for (IListItem obj : cartList) {
				View tempItemView;
				if (indexController == 0) {
					tempItemView = rowInflater.inflate(R.layout.cart_top, null);
				} else if (indexController == cartList.size() - 1) {
					tempItemView = rowInflater.inflate(R.layout.cart_bottom,
							null);
				} else {
					tempItemView = rowInflater.inflate(R.layout.cart_middle,
							null);
				}
				setupItem(tempItemView, obj, indexController);
				tempItemView.setClickable(obj.isClickable());
				viewListContainer.addView(tempItemView);
				indexController++;
			}
		} else if (cartList.size() == 1) {
			// when the list has only one item
			View tempItemView = rowInflater.inflate(R.layout.cart_single, null);
			IListItem obj = cartList.get(0);
			setupItem(tempItemView, obj, indexController);
			tempItemView.setClickable(obj.isClickable());
			viewListContainer.addView(tempItemView);
		}
	}

	private void setupItem(View view, IListItem item, int index) {
		if (item instanceof CartBasicItem) {
			CartBasicItem tempItem = (CartBasicItem) item;
			setupBasicItem(view, tempItem, indexController);
		} else if (item instanceof ViewItem) {
			ViewItem tempItem = (ViewItem) item;
			setupViewItem(view, tempItem, indexController);
		}
	}

	/**
	 * 
	 * @param view
	 * @param item
	 * @param index
	 */
	private void setupBasicItem(final View view, final CartBasicItem item,
			int index) {

		Log.d("OrderDetailTableView", "setupBasicItem() is called");
		if (item.getImageUrl() != null) {
			Log.d("OrderDetailTableView", "item.getDrawable() is called");
			((ImageView) view.findViewById(R.id.image))
					.setImageBitmap(BitmapFactory.decodeFile(item
							.getImageUrl().replace("http://rouge3351.cafe24.com/image",
									context.getCacheDir().toString())));
		}
		if (item.getOrderedProductName() != null) {
			Log.d("OrderDetailTableView", "item.getSubtitle() is called");
			((TextView) view.findViewById(R.id.txtvOrderedProductName))
					.setText(item.getOrderedProductName());
		} else {
			Log.d("OrderDetailTableView", "else is called");
			((TextView) view.findViewById(R.id.subtitle))
					.setVisibility(View.GONE);
		}
		TextView txtvIndex = (TextView) view.findViewById(R.id.itemCount);
		txtvIndex.setTag(index);

		// 상품 세부정보 Layout
		RelativeLayout cartDetailLayout = (RelativeLayout) view
				.findViewById(R.id.cartDetailLayout);
		if (cartDetailLayout != null)
			cartDetailLayout.setVisibility(View.GONE);
		else
			Log.d("OrderDetailTableView", "cartDetailLayout isn't null");

		// 인덱스 저장
		view.setTag(index);

		// 삭제 버튼
		Button btnDelete = (Button) view.findViewById(R.id.btnDeleteFromCart);
		btnDelete.setTag(index);
		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				AlertDialog.Builder ab = new AlertDialog.Builder(context);
				ab.setTitle("물품 삭제 확인");
				ab.setMessage("삭제 하시겠습니까?");
				ab.setPositiveButton("확인", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int index = Integer.valueOf("" + v.getTag());
						Log.d("CartTableView - Delete", "삭제 시작 index = " + index);
						Message msg = Message.obtain(Cart.totalPricehandler,
								Constants.TOTAL_PRICE_RESET);
						Cart.totalPricehandler.sendMessage(msg);
						CafeNoa cafeNoa = (CafeNoa) context.getApplicationContext();
						cafeNoa.removeProductInCartList(index);
						removeProductInCart(index);
						commit();
						dialog.cancel();
					}
				});

				ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
				
				AlertDialog alert = ab.create();
				alert.show();
			}
		});

		// CoffeAmount가 바뀌면 가격이 자동으로 책정됨
		EditText edtCoffeeAmount = (EditText) view
				.findViewById(R.id.edtCoffeeAmount);
		edtCoffeeAmount.addTextChangedListener(new TextWatcher() {
			TextView txtvPrice = (TextView) view
					.findViewById(R.id.txtvIndividualPrice);

			TextView txtvContractCoffeeAmount = (TextView) view
					.findViewById(R.id.txtvContractCoffeeAmount);
			final int pricePerOne = item.getPrice();
			int beforeCoffee;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Log.d("addTextChangedListener",
						"addTextChangedListener is called + nowPrice"
								+ txtvPrice.getText());
				int afterCoffee = Integer.valueOf(s.toString());

				int nowPrice = Integer.valueOf(txtvPrice.getText() + "");

				Message msg;
				if (afterCoffee > beforeCoffee) {
					msg = Message.obtain(Cart.totalPricehandler,
							Constants.TOTAL_PRICE_ADDITION, pricePerOne);
					nowPrice += pricePerOne;
				} else {
					msg = Message.obtain(Cart.totalPricehandler,
							Constants.TOTAL_PRICE_SUBTRACTION, pricePerOne);
					nowPrice -= pricePerOne;
				}
				Cart.totalPricehandler.sendMessage(msg);
				txtvContractCoffeeAmount.setText(s + "잔");
				txtvPrice.setText(nowPrice + "");

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				beforeCoffee = Integer.valueOf(s.toString());
				Log.d("beforeCoffee", "beforeCoffee = " + beforeCoffee);
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		edtCoffeeAmount.setText("1");

		// 잔수 증/감 버튼
		Button btnCoffeeAmountDown = (Button) view
				.findViewById(R.id.btnCoffeeAmountDown);

		btnCoffeeAmountDown.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				View Parent = (View) v.getParent();
				EditText edtCoffeeAmount = (EditText) Parent
						.findViewById(R.id.edtCoffeeAmount);
				int nCoffeeAmount = Integer.valueOf(String
						.valueOf(edtCoffeeAmount.getText()));

				// 0잔인데 -버튼을 누르면 카트에서 삭제할건지 물어보는 루틴
				if (nCoffeeAmount == MIN_COFFEE_AMOUNT) {

				} else {
					nCoffeeAmount--;
					edtCoffeeAmount.setText(nCoffeeAmount + "");
				}
			}
		});

		Button btnCoffeeAmountUp = (Button) view
				.findViewById(R.id.btnCoffeeAmountUp);
		btnCoffeeAmountUp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				View Parent = (View) v.getParent();
				EditText edtCoffeeAmount = (EditText) Parent
						.findViewById(R.id.edtCoffeeAmount);
				int nCoffeeAmount = Integer.valueOf(String
						.valueOf(edtCoffeeAmount.getText()));
				if (nCoffeeAmount != MAX_ADDITIONAL_AMOUNT) {
					nCoffeeAmount++;
					edtCoffeeAmount.setText(nCoffeeAmount + "");
				}
			}
		});

		String strOption = item.getProductOption();
		StringTokenizer stringTokenizer = new StringTokenizer(strOption, "/");
		String tokenizedString;
		while (stringTokenizer.hasMoreElements()) {
			tokenizedString = (String) stringTokenizer.nextToken();
			LinearLayout llOption = (LinearLayout) view
					.findViewById(R.id.llOption);
			OptionBasicItem optionBasicItem = new OptionBasicItem(context,
					view, tokenizedString.split(",")[0],
					Integer.valueOf(tokenizedString.split(",")[1].trim()));
			optionBasicItem.setGravity(Gravity.RIGHT);
			llOption.addView(optionBasicItem);
		}

		// 샷수 변경시 가격 변경

		// TextView txtvOption1 = (TextView)
		// view.findViewById(R.id.txtvOption1Amount);
		// txtvOption1.setText(tokenizedString);
		// EditText edtShotAmount = (EditText) view
		// .findViewById(R.id.edtOption1Amount);
		// edtShotAmount.addTextChangedListener(new TextWatcher() {
		// TextView txtvPrice = (TextView) view
		// .findViewById(R.id.txtvIndividualPrice);
		//
		// final int pricePerOneShot = 500;
		// int beforeShot;
		//
		// @Override
		// public void onTextChanged(CharSequence s, int start, int before,
		// int count) {
		// Log.d("addTextChangedListener",
		// "addTextChangedListener is called");
		// int afterShot = Integer.valueOf(s.toString());
		// int nowPrice = Integer.valueOf(txtvPrice.getText() + "");
		// Message msg;
		// if (afterShot > beforeShot) {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_ADDITION, pricePerOneShot);
		// nowPrice+=pricePerOneShot;
		// } else {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_SUBTRACTION, pricePerOneShot);
		// nowPrice-=pricePerOneShot;
		// }
		// Cart.totalPricehandler.sendMessage(msg);
		// txtvPrice.setText(nowPrice+"");
		//
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start, int count,
		// int after) {
		// beforeShot = Integer.valueOf(s.toString());
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		//
		// // 샷수 증/감 버튼
		// Button btnShotAmountDown = (Button) view
		// .findViewById(R.id.btnOption1AmountDown);
		// btnShotAmountDown.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtCoffeeAmount = (EditText) Parent
		// .findViewById(R.id.edtOption1Amount);
		// int nShotAmount = Integer.valueOf(String
		// .valueOf(edtCoffeeAmount.getText()));
		// if (nShotAmount != MIN_ADDITIONAL_AMOUNT) {
		// nShotAmount--;
		// edtCoffeeAmount.setText(nShotAmount + "");
		// }
		// }
		// });
		//
		// Button btnShotAmountUp = (Button) view
		// .findViewById(R.id.btnOption1AmountUp);
		// btnShotAmountUp.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtCoffeeAmount = (EditText) Parent
		// .findViewById(R.id.edtOption1Amount);
		// int nShotAmount = Integer.valueOf(String
		// .valueOf(edtCoffeeAmount.getText()));
		// if (nShotAmount != MAX_ADDITIONAL_AMOUNT) {
		// nShotAmount++;
		// edtCoffeeAmount.setText(nShotAmount + "");
		// }
		// }
		// });

		// // CreamAmount가 바뀌면 가격이 자동으로 책정됨
		// EditText edtCreamAmount = (EditText) view
		// .findViewById(R.id.edtOption2Amount);
		// edtCreamAmount.addTextChangedListener(new TextWatcher() {
		// TextView txtvPrice = (TextView) view
		// .findViewById(R.id.txtvIndividualPrice);
		//
		// final int pricePerOneCream = 500;
		// int beforeCoffee;
		//
		// @Override
		// public void onTextChanged(CharSequence s, int start, int before,
		// int count) {
		// Log.d("addTextChangedListener",
		// "addTextChangedListener is called + nowPrice" + txtvPrice.getText());
		// int afterCoffee = Integer.valueOf(s.toString());
		//
		// int nowPrice = Integer.valueOf(txtvPrice.getText() + "");
		//
		// Message msg;
		// if (afterCoffee > beforeCoffee) {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_ADDITION, pricePerOneCream);
		// nowPrice += pricePerOneCream;
		// } else {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_SUBTRACTION, pricePerOneCream);
		// nowPrice -= pricePerOneCream;
		// }
		// Cart.totalPricehandler.sendMessage(msg);
		// txtvPrice.setText(nowPrice + "");
		//
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start, int count,
		// int after) {
		// beforeCoffee = Integer.valueOf(s.toString());
		// Log.d("beforeCoffee", "beforeCoffee = " + beforeCoffee);
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		// // 크림 증/감 버튼
		// Button btnCreamAmountDown = (Button) view
		// .findViewById(R.id.btnOption2AmountDown);
		// btnCreamAmountDown.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtCoffeeAmount = (EditText) Parent
		// .findViewById(R.id.edtOption2Amount);
		// int nCreamAmount = Integer.valueOf(String
		// .valueOf(edtCoffeeAmount.getText()));
		// if (nCreamAmount != MIN_ADDITIONAL_AMOUNT) {
		// nCreamAmount--;
		// edtCoffeeAmount.setText(nCreamAmount + "");
		// }
		// }
		// });
		//
		// Button btnCreamAmountUp = (Button) view
		// .findViewById(R.id.btnOption2AmountUp);
		// btnCreamAmountUp.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtCoffeeAmount = (EditText) Parent
		// .findViewById(R.id.edtOption2Amount);
		// int nCreamAmount = Integer.valueOf(String
		// .valueOf(edtCoffeeAmount.getText()));
		// if (nCreamAmount != MAX_ADDITIONAL_AMOUNT) {
		// nCreamAmount++;
		// edtCoffeeAmount.setText(nCreamAmount + "");
		// }
		// }
		// });
		//
		// // CreamAmount가 바뀌면 가격이 자동으로 책정됨
		// EditText edtBothAmount = (EditText) view
		// .findViewById(R.id.edtOption3Amount);
		// edtBothAmount.addTextChangedListener(new TextWatcher() {
		// TextView txtvPrice = (TextView) view
		// .findViewById(R.id.txtvIndividualPrice);
		//
		// final int pricePerOneBoth = 1000;
		// int beforeCoffee;
		//
		// @Override
		// public void onTextChanged(CharSequence s, int start, int before,
		// int count) {
		// Log.d("addTextChangedListener",
		// "addTextChangedListener is called + nowPrice" + txtvPrice.getText());
		// int afterCoffee = Integer.valueOf(s.toString());
		//
		// int nowPrice = Integer.valueOf(txtvPrice.getText() + "");
		//
		// Message msg;
		// if (afterCoffee > beforeCoffee) {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_ADDITION, pricePerOneBoth);
		// nowPrice += pricePerOneBoth;
		// } else {
		// msg = Message.obtain(Cart.totalPricehandler,
		// Constants.TOTAL_PRICE_SUBTRACTION, pricePerOneBoth);
		// nowPrice -= pricePerOneBoth;
		// }
		// Cart.totalPricehandler.sendMessage(msg);
		// txtvPrice.setText(nowPrice + "");
		//
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start, int count,
		// int after) {
		// beforeCoffee = Integer.valueOf(s.toString());
		// Log.d("beforeCoffee", "beforeCoffee = " + beforeCoffee);
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		// // 둘다 증/감 버튼
		// Button btnBothAmountDown = (Button) view
		// .findViewById(R.id.btnBothOption3Down);
		// btnBothAmountDown.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtBothAmount = (EditText) Parent
		// .findViewById(R.id.edtOption3Amount);
		// int nBothAmount = Integer.valueOf(String.valueOf(edtBothAmount
		// .getText()));
		// if (nBothAmount != MIN_ADDITIONAL_AMOUNT) {
		// nBothAmount--;
		// edtBothAmount.setText(nBothAmount + "");
		// }
		// }
		// });
		//
		// Button btnBothAmountUp = (Button) view
		// .findViewById(R.id.btnOption3AmountUp);
		// btnBothAmountUp.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// View Parent = (View) v.getParent();
		// EditText edtBothAmount = (EditText) Parent
		// .findViewById(R.id.edtOption3Amount);
		// int nBothAmount = Integer.valueOf(String.valueOf(edtBothAmount
		// .getText()));
		// if (nBothAmount != MAX_ADDITIONAL_AMOUNT) {
		// nBothAmount++;
		// edtBothAmount.setText(nBothAmount + "");
		// }
		// }
		// });

		if (item.isClickable()) {
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View view) {
					if (mClickListener != null)
						mClickListener.onClick((Integer) view.getTag());
				}

			});
		}
		// checkbox 추가하면서 필요없는 루틴일 수 있음
		// else {
		// Log.d("OrderDetailTableView", "item.isSelectedProduct() = " +
		// item.isSelectedProduct());
		// ((CheckBox)
		// view.findViewById(R.id.cbChoosedProduct)).setChecked(item.isSelectedProduct());
		// }
	}

	/**
	 * 
	 * @param view
	 * @param itemView
	 * @param index
	 */
	private void setupViewItem(View view, ViewItem itemView, int index) {
		if (itemView.getView() != null) {
			LinearLayout itemContainer = (LinearLayout) view
					.findViewById(R.id.itemContainer);
			itemContainer.removeAllViews();
			// itemContainer.removeAllViewsInLayout();
			itemContainer.addView(itemView.getView());

			if (itemView.isClickable()) {
				itemContainer.setTag(index);
				itemContainer.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						if (mClickListener != null)
							mClickListener.onClick((Integer) view.getTag());
					}
				});
			}
		}
	}

	/**
	 * Cart에 있는 상품의 갯수를 리턴
	 * 
	 * @return 상품 갯수
	 */
	public int getProductCountInCart() {
		return cartList.size();
	}

	/**
	 * 전체 CartList를 삭제
	 */
	public void clearCartList() {
		cartList.clear();
		viewListContainer.removeAllViews();
	}

	public void removeProductInCart(int index) {
		cartList.remove(index);
		viewListContainer.removeAllViews();
	}

	public interface ClickListener {
		void onClick(int index);
	}

	/**
	 * 
	 * @param listener
	 */
	public void setClickListener(ClickListener listener) {
		this.mClickListener = listener;
	}

	/**
	 * 
	 */
	public void removeClickListener() {
		this.mClickListener = null;
	}

	public LinearLayout getViewListContainer() {
		return viewListContainer;
	}

	public void addProductInCart(CartBasicItem cartBasicItem) {
		cartList.add(cartBasicItem);
	}

	public List<IListItem> getCartList() {
		return cartList;
	}

}